package com.echoesnet.echoesshortvideo.Fragments;

import android.app.Activity;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.echoesnet.echoesshortvideo.Activities.PlayVideoActivity;
import com.echoesnet.echoesshortvideo.Persistence.TinyVideoInfoEntity;
import com.echoesnet.echoesshortvideo.R;
import com.echoesnet.echoesshortvideo.Utils.ToastUtils;
import com.echoesnet.echoesshortvideo.ViewModels.ListOfVideoClipsViewModel;
import com.echoesnet.echoesshortvideo.views.adapters.VideoListAdapter;
import com.marshalchen.ultimaterecyclerview.UltimateRecyclerView;
import com.marshalchen.ultimaterecyclerview.ui.emptyview.emptyViewOnShownListener;
import com.shizhefei.fragment.LazyFragment;

import java.util.List;

public class HomePageVideoListFragment extends LazyFragment
{
    private final String TAG = HomePageVideoListFragment.class.getSimpleName();

    public static final String INTENT_STRING_TABNAME = "intent_String_tabName";
    public static final String INTENT_INT_POSITION = "intent_int_position";

    private Activity mActivity;
    private ListOfVideoClipsViewModel viewModel;
    private UltimateRecyclerView urvList;
    private VideoListAdapter mListAdapter;

    private String tabName;
    private int position;

    public ListOfVideoClipsViewModel getViewModel()
    {
        return viewModel;
    }

    @Override
    protected View getPreviewLayout(LayoutInflater inflater, ViewGroup container)
    {
        return inflater.inflate(R.layout.layout_preview, container, false);
    }

    @Override
    protected void onCreateViewLazy(Bundle savedInstanceState)
    {
        super.onCreateViewLazy(savedInstanceState);
        mActivity = getActivity();

        tabName = getArguments().getString(INTENT_STRING_TABNAME);
        position = getArguments().getInt(INTENT_INT_POSITION);
        setContentView(R.layout.frg_tab_homepage);

        urvList = (UltimateRecyclerView) findViewById(R.id.urvList);


        viewModel = ViewModelProviders.of(this).get(ListOfVideoClipsViewModel.class);
        viewModel.list().observe(this, list -> {
            urvList.setRefreshing(false);
            if (list != null)
            {
                setupList(list);
                if (list.isEmpty())
                {
                    urvList.showEmptyView();
                }
                else
                {
                    urvList.hideEmptyView();
                }

//                Toast.makeText(mActivity, list.size()+"", Toast.LENGTH_SHORT).show();
            }
        });

        viewModel.loadmore().observe(this, hasMore -> {
            if (mListAdapter == null)
                return;

            Log.i("lllllMore", "T:" + System.currentTimeMillis() + " hasMore " + hasMore);
            if (hasMore)
            {

            }
            else
            {
                urvList.disableLoadmore(); // 监听有关
//                mListAdapter.enableLoadMore(false); // view 有关；
//                mListAdapter.getCustomLoadMoreView().setVisibility(View.GONE);
                mListAdapter.internalExecuteLoadingView();
            }
        });
        viewModel.getCheckVideoResult().observe(this, result -> {
            if (result != null)
            {
                if ("0".equals(result.get("result")))
                {
                    Intent intent = new Intent(mActivity, PlayVideoActivity.class);
                    intent.putExtra("videoId", result.get("videoId"));
                    intent.putExtra("openSource", result.get("openSource"));
                    startActivity(intent);
                    mActivity.overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
                }
                else
                {
                    ToastUtils.showShort("该视频已被删除");
                }
            }



        });

        viewModel.requestRefresh();
    }

    @Override
    protected void onResumeLazy()
    {
        super.onResumeLazy();
    }

    @Override
    protected void onDestroyViewLazy()
    {
        super.onDestroyViewLazy();
    }

    public void setupList(List<TinyVideoInfoEntity> list)
    {
        if (null == mListAdapter)
        {
            mListAdapter = new VideoListAdapter(mActivity, list);

            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mActivity)
            {
                @Override
                protected int getExtraLayoutSpace(RecyclerView.State state)
                {
                    return 10;
                }
            };
//            GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 2) {
//                @Override
//                protected int getExtraLayoutSpace(RecyclerView.State state) {
//                    return 300;
//                }
//            };


            urvList.setLayoutManager(linearLayoutManager);
            urvList.reenableLoadmore();
            urvList.setHasFixedSize(false);
            urvList.setEmptyView(R.layout.empty_view, UltimateRecyclerView.EMPTY_CLEAR_ALL, new emptyViewOnShownListener()
            {
                @Override
                public void onEmptyViewShow(View mView)
                {
//                    ((TextView) mView.findViewById(R.id.tvDesc)).setText("暂时没有新朋友，上拉加载试试");
                }
            });
            urvList.setLoadMoreView(R.layout.item_loadmore);
//            mListAdapter.setCustomLoadMoreView(LayoutInflater.from(mActivity).inflate(R.layout.item_loadmore, null));
//            mListAdapter.enableLoadMore(true);
            urvList.setAdapter(mListAdapter);
//          urvList.addOnScrollListener(new RecyclerView.OnScrollListener() {
//                @Override
//                public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
//
//                }
//            });
            urvList.setOnLoadMoreListener((itemsCount, maxLastVisiblePosition) -> {
                viewModel.requestMore();
//                Log.i("lllllMore","T:"+System.currentTimeMillis());

            });

            urvList.setDefaultOnRefreshListener(() -> {
                urvList.reenableLoadmore(); // 监听有关
//                mListAdapter.enableLoadMore(true); // view 有关；
//                mListAdapter.getCustomLoadMoreView().setVisibility(View.VISIBLE);
                viewModel.requestRefresh();
            });

            mListAdapter.setOnItemClickListener((view, infoEntity, position) -> {
                String a = "";
                switch (view.getId())
                {
                    case R.id.tvNickNameLeft:
                    case R.id.tvNickNameRight:
                        a = "R.id.tvNickName";
                        break;
                    case R.id.ivAvatarLeft:
                    case R.id.ivAvatarRight:
                        a = "R.id.ivAvatar";
                        break;
                    case R.id.ivCoverImgLeft:
                    case R.id.ivCoverImgRight:
                        a = "R.id.ivCoverImg";
                        viewModel.checkVideoState(infoEntity.getVideoId(), "0");
                        break;
                }

                String msg = "vid:" + a + " | info:" + infoEntity.toString();
//                Toast.makeText(mActivity, msg, Toast.LENGTH_SHORT).show();
            });

            registerForContextMenu(urvList);

        }
        else
        {
            mListAdapter.setDataList(list);
        }
        mListAdapter.notifyDataSetChanged();
    }
}
